<template>
  <div class="container-box">
    <el-form ref="orderForm" :inline="true" :model="formData" :disabled="isEdit" :rules="rules" class="demo-form-inline">
      <div class="customer-info">
        <el-form-item label="客户" prop="customer_id">
          <el-select v-model="formData.customer_id" filterable>
            <el-option v-for="item in customerList" :key="item.id" :label="item.company_name" :value="item.id" />
          </el-select>
          <el-tooltip :disabled="showCustomerRecord" v-show="!showCustomerRecord" effect="dark" :content="getCustomerRecord()" placement="right">
            <span style="padding: 0 20px;"><i class="el-icon-info" /></span>
          </el-tooltip>
          <!-- <el-input v-model="formData.customer_id" /> -->
        </el-form-item>
        <el-form-item label="出货仓库" prop="store_house_id">
          <el-select v-model="formData.store_house_id" filterable>
            <el-option v-for="item in storeHouseList" :key="item.id" :label="item.store_house_name" :value="item.id" />
          </el-select>
          <!-- <el-input v-model="formData.customer_id" /> -->
        </el-form-item>
      </div>
      <el-row>
        <el-button v-if="pageParams.operateType !== 'add'" type="primary" @click="handleTableOp('orderDetail')">刷新</el-button>
        <el-button v-if="pageParams.operateType === 'add'" type="primary" @click="handleTableOp('addGoods')">添加商品</el-button>
        <!-- <el-button v-if="pageParams.operateType === 'add'" type="primary" @click="handleTableOp('print')">打印</el-button> -->
        <el-button v-if="pageParams.operateType === 'add'" type="primary" @click="handleTableOp('addOrder')">提交订单</el-button>
        <!-- <el-button v-print="'#print_demo'" type="primary">打印</el-button> -->
      </el-row>
      <div class="table-box">
        <!-- @current-change="handleCurrentChange" @cell-dblclick="cellDblclick" -->
        <el-table ref="tableRef" class="form-table" :data="formData.goods_list" border highlight-current-row show-summary :summary-method="getSummaries" width="100%">
          <el-table-column type="index" width="60" align="center" />
          <el-table-column label="商品名称" align="center" prop="goods_name" width="200px">
            <template slot-scope="scope">
              <div class="flex_row _center __between" style="padding: 0 10px">
                <div class="column-value" @dblclick="handleDblclick(scope.$index, 'goods_name')">{{ handleRowResult('goods_name', scope.row) }}</div>
                <!-- <el-button type="primary" icon="el-icon-delete" @click="handleDelRow(scope.$index)"></el-button> -->
                <i class="el-icon-close close_goods_row" @click="handleDelRow(scope.$index)"></i>
              </div>

              <!-- <el-form-item :prop="`goods_list.${scope.$index}.goods_id`" label="">
                <el-select v-model="formData.goods_list[scope.$index].goods_id" filterable>
                  <el-option v-for="item in goodsList" :key="item.id" :label="item.full_goods_name || item.goods_name" :value="item.id" />
                </el-select>
              </el-form-item> -->
            </template>
          </el-table-column>
          <!-- <el-table-column label="规格" align="center" prop="goods_sku">
            <template slot-scope="scope">
              <div>{{ scope.row.goods_sku }}</div>
            </template>
          </el-table-column> -->
          <el-table-column label="出货仓库" align="center" prop="store_house_id" width="200px">
            <template slot-scope="scope">
              <el-form-item :prop="`goods_list.${scope.$index}.store_house_id`" :rules="rules.g_store_house_id">
                <el-select v-model="scope.row.store_house_id" filterable>
                  <el-option v-for="item in storeHouseList" :key="item.id" :label="item.store_house_name" :value="item.id" />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="数量" align="center" prop="goods_num" width="100px">
            <template slot-scope="scope">
              <el-form-item :prop="`goods_list.${scope.$index}.goods_num`">
                <!-- <el-input v-model.number="scope.row.goods_num" @change="changeInput($event, scope.$index, 'goods_num')">
                  <template slot="append">{{ scope.row.unit_name }}</template>
                </el-input> -->
                <!-- <el-input v-model.number="scope.row.goods_num" @change="changeInput($event, scope.$index, 'goods_num')" /> -->
                <el-input-number v-model="scope.row.goods_num" :controls="false" :readonly="false" :min="1" :step="1" @change="changeInput($event, scope.$index, 'goods_num')" />
                
                <!-- <el-input-number v-model="scope.row.goods_num" :controls="false">
                  <template slot="append">{{ scope.row.unit_name }}</template>
                </el-input-number> -->
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="数量2" align="center" prop="goods_num2" width="100px">
            <template slot-scope="scope">
              <el-input v-model.number="scope.row.goods_num2" @change="changeInput($event, scope.$index, 'goods_num2')" />
              <!-- <div class="">{{ handleRowResult('goods_num2', scope.row) }}</div> -->
            </template>
          </el-table-column>
          <el-table-column label="单价" align="center" prop="goods_price" width="100px">
            <template slot-scope="scope">
              <el-form-item :prop="`goods_list.${scope.$index}.goods_price`" :rules="rules.goods_price">
                <!-- <el-input-number v-model="scope.row.goods_price" :controls="false" :min="0.01" :step="0.01" @change="changeInput($event, scope.$index, 'goods_price')" /> -->
                <el-input v-model="scope.row.goods_price" :controls="false" @change="changeInput($event, scope.$index, 'goods_price')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="金额" align="center" prop="total_price" width="100px">
            <template slot-scope="scope">
              <el-form-item :prop="`goods_list.${scope.$index}.total_price`">
                <!-- <el-input-number v-model="scope.row.total_price" :controls="false" :step="1" @change="changeInput($event, scope.$index, 'total_price')" /> -->
                <el-input v-if="scope.row.sku_id" v-model="scope.row.total_price" :controls="false" :min="0.01" :step="1" @change="changeInput($event, scope.$index, 'total_price')" />
                <!-- <div v-else /> -->
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="折扣" align="center" prop="discount">
            <template slot-scope="scope">
              <el-form-item :prop="`goods_list.${scope.$index}.discount`">
                <el-input-number v-model="scope.row.discount" :controls="false" :min="0.01" :step="0.01" @change="changeInput($event, scope.$index, 'discount')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="折后单价" align="center" prop="discount_price" width="100px">
            <template slot-scope="scope">
              <el-form-item :prop="`goods_list.${scope.$index}.discount_price`">
                <el-input v-model="scope.row.discount_price" :disabled="true" />
                <!-- <el-input-number v-model="scope.row.discount_price" :controls="false" :min="0.01" :step="0.01" /> -->
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="折后金额" align="center" prop="discount_total_price" width="100px">
            <template slot-scope="scope">
              <el-form-item :prop="`goods_list.${scope.$index}.discount_total_price`">
                <!-- <el-input-number v-model="scope.row.discount_total_price" :controls="false" :min="0.01" :step="0.01" /> -->
                <el-input v-model.number="scope.row.discount_total_price" :disabled="true" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remarks" width="100px">
            <template slot-scope="scope">
              <el-form-item :prop="`goods_list.${scope.$index}.remarks`">
                <el-input v-model="scope.row.remarks" />
              </el-form-item>
            </template>
          </el-table-column>

          <!-- <template v-for="(item, index) in columns.filter(d => d.isTable)">
          <el-table-column :key="index" :prop="item.key" :label="item.title">
            <template slot-scope="scope">
              <div v-if="item.key === ''" class="">{{ scope.row[item.key] }}</div>
              <div v-else class="">{{ handleRowResu lt(item, scope.row) }}</div>
            </template>
          </el-table-column>
        </template> -->
        </el-table>
      </div>
    </el-form>
    <v-goods-dialog ref="goodsDialofRef" @callback="handleAddComCb" />
    <!-- <div class="print-mould-box">
      <v-print-mould :order-data="formData" :columns="columns" />
    </div> -->
  </div>
</template>

<script>
import { goodsIndex } from '@/api/goods';
import { orderDetail, orderAdd, orderEdit } from '@/api/order';
import curde from '@/mixins/curde';

import GoodsDialog from '@/views/goods/goodsDialog.vue'
import PrintMould from './printMould.vue'

export default {
  name: 'OrderEdit',
  components: {
    vGoodsDialog: GoodsDialog,
    vPrintMould: PrintMould
  },
  mixins: [curde],
  data() {
    const goodsItem = (data) => {
      let goods_price = '';
      if (this.goods_record && this.goods_record[data.id]) {
        const skuList = this.goods_record[data.id] || [];
        const selGoods = skuList.find(d => d.goods_sku === data?.attrConfigValue?.sku);
        goods_price = selGoods ? selGoods?.goods_price : 0;
        console.log('goodsItem--goods_price==', goods_price, selGoods)
      }
      return {
        sku_id: data?.sku_id || '',
        sku: data?.sku || '',
        goods_id: data?.id || '',
        goods_name: data?.goods_name || '',
        goods_sku: data?.attrConfigValue?.sku || '',
        goods_num: 1,
        goods_num2: 0,
        goods_price: goods_price,
        total_price: '',
        discount: 1,
        discount_price: '',
        discount_total_price: '',
        store_house_id: '',
        order_type: '',
        remarks: '',
        unit_name: data?.unit_name || '',
        unit_name2: data?.unit_name2 || '',
        unit_convert: data?.unit_convert || 1,
        unit_convert2: data?.unit_convert2 || 1,
        config: this.$json.cloneDeep(data)
      }
    };
    return {
      printObj: {
        id: 'print_demo',
        popTitle: '打印的标题'
        // extraCss: 'https://www.google.com,https://www.google.com',
        // extraHead: '<meta http-equiv="Content-Language"content="zh-cn"/>'
      },
      columns: [
        { title: '商品名称', key: 'goods_name', type: 'text', width: '200px', clearable: true, isFilter: true, isTable: true, isForm: false, isPrint: true },
        { title: '商品规格', key: 'goods_sku', type: 'text', clearable: true, isFilter: false, isTable: true, isForm: false, isPrint: false },
        { title: '包装规格', key: 'unit_convert2', type: 'number', clearable: true, isFilter: false, isTable: false, isForm: false, isPrint: true },
        { title: '数量', key: 'goods_num', type: 'number', width: '100px', clearable: true, isFilter: false, isTable: true, isForm: false, isPrint: true },
        { title: '数量2', key: 'goods_num2', type: 'number', width: '100px', clearable: true, isFilter: false, isTable: true, isForm: false, isPrint: true },

        { title: '基本单位', key: 'unit_name', type: 'text', isFilter: false, isTable: false, isForm: true, isPrint: false },
        { title: '辅助单位', key: 'unit_name2', type: 'text', isFilter: false, isTable: false, isForm: true, isPrint: false },
        { title: '基本单位换算', key: 'unit_convert', type: 'number', isFilter: false, isTable: false, isForm: true, isPrint: false },
        { title: '辅助单位换算', key: 'unit_convert2', type: 'number', isFilter: false, isTable: false, isForm: true, isPrint: false },

        { title: '单价', key: 'goods_price', type: 'number', width: '100px', clearable: true, isFilter: false, isTable: true, isForm: false, isPrint: true },
        { title: '小计金额', key: 'total_price', type: 'number', width: '100px', clearable: true, isFilter: false, isTable: true, isForm: false, isPrint: true },
        { title: '折扣', key: 'discount', type: 'number', clearable: true, isFilter: false, isTable: true, isForm: false, isPrint: false },
        { title: '出货仓库', key: 'store_house_id', type: 'text', width: '200px', clearable: true, isFilter: true, isTable: true, isForm: false, isPrint: false },
        { title: '备注', key: 'remarks', type: 'text', clearable: true, isFilter: true, isTable: true, isForm: false, isPrint: true }
      ],
      list: [],
      formData: {
        customer_id: '',
        company_name: '',
        store_house_id: '',
        goods_list: [],
        total_num: 0,
        total_price: 0,
        discount: 1,
        remarks: '',
        order_type: '',
        status: '1',
        create_time: this.$moment(new Date()).format('YYYY-MM-DD')
      },
      goodsList: [],
      goods_list: [],
      // goods_list: [],
      rules: {
        customer_id: [{ required: true, message: '请选择订单客户', trigger: ['change', 'blur'] }],
        goods_name: [{ required: true, message: '请选择商品', trigger: ['change', 'blur'] }],
        g_store_house_id: [{ required: true, message: '请选择出货仓库', trigger: ['change', 'blur'] }],
        goods_num: [{ required: true, type: 'number', min: 1, message: '请输入商品数量', trigger: ['change', 'blur'] }],
        goods_price: [{ required: true, type: 'number', min: 0, message: '请输入商品金额', trigger: ['change', 'blur'] }]
      },
      goodsItem: (e) => goodsItem(e),
      goodsIndex: -1,
      saving: false,
      goods_record: {},
      showCustomerRecord: true
    };
  },
  computed: {
    isEdit() {
      if (['add', 'edit'].includes(this.pageParams?.operateType)) {
        return false;
      }
      else {
        return true;
      }
    },
    // 客户列表
    customerList() {
      const list = this.$store.state.customer.list || [];
      console.log('customerList==', list);
      if (list.length === 0) {
        return [];
      }
      if (this.$route.query.oType === '1') {
        return list.filter(d => ['1', '3'].includes(d.customer_type))
      }
      else if (this.$route.query.oType === '2') {
        return list.filter(d => ['2', '3'].includes(d.customer_type))
      }
      return list;
    },
    storeHouseList() {
      const storeHouseList = this.$store.getters.storeHouseList?.data || [];
      this.updataComplete('storeHouseList', storeHouseList);
      return storeHouseList
    },
    customerData() {
      let customerData;
      if (this.formData.customer_id) {
        customerData = this.customerList.find(d => d.id === this.formData.customer_id);
      }
      return customerData;
    }
  },
  watch: {
    '$route.query': {
      handler({ oType }) {
        console.log('query==', oType);
        this.formData.order_type = oType;
      },
      deep: true,
      immediate: true
    },
    'formData.customer_id': {
      handler(val) {
        if (val) {
          console.log('customer_id==', val, this.customerList);
          const customer = this.customerList.find(d => d.id === val+'');
          console.log('customer==', customer);
          this.formData.company_name = customer?.company_name;
          const goods_list = this.formData?.goods_list || [];
          const skuOrder = this.customerData?.skuOrder || [];
          if (goods_list.length && skuOrder.length) {
            // 记录自动变更价格的商品 以便提醒操作员
            let message = '';
            goods_list.forEach(d => {
              const { sku_id = 0, goods_price, discount, goods_name, sku } = skuOrder.find(o => o.sku_id === d.sku_id) || {};
              if (sku_id && goods_price && discount > 0.1) {
                d.goods_price = goods_price;
                d.discount = discount;
                d.discount_price = goods_price * discount;
                message += `<strong>${goods_name} ${sku}<strong> 价格已自动更改历史价格 <strong>${goods_price}<strong> <br/><br/>`;
              }
            })
            if (message) {
              this.$message({
                dangerouslyUseHTMLString: true,
                message,
                type: 'info'
              });
            }
          }
        }
        else {
          this.formData.company_name = '';
        }
        console.log('watch--formData.customer_id==', this.formData);
      },
      deep: true
    },
    'formData.store_house_id': {
      handler(val) {
        if (val) {
          console.log('formData.store_house_id--val==', val);
          if (this.formData.goods_list && this.formData.goods_list.length > 0) {
            const goods_list = this.formData.goods_list;
            let isFlag = false;
            goods_list.forEach(d => {
              if (!d.store_house_id) {
                d.store_house_id = val;
                isFlag = true;
              }
            })
            console.log('formData.store_house_id--goods_list==', goods_list, isFlag);
            if (isFlag) {
              this.$set(this.formData, 'goods_list', goods_list)
            }
          }
        }
        console.log('watch--formData.store_house_id==', this.formData);
      },
      deep: true
    },
  },
  created() {
    console.log('orderAdd--this.pageParams--2==', this.pageParams, this.curStore, this.isEdit);
    if (this.pageParams?.type !== 'add') {
      this.getGoods();
    }
    if (this.pageParams?.id > 0) {
      this.getOrderDetails();
    }
    this.initFun();
  },
  updated() {
    this.$nextTick(() => {
      this.$refs.tableRef.doLayout();
    })
  },
  methods: {
    // 判断客户是否有购买历史 有则自动补充价格
    handleGoodsPrice(goods_id, sku_id) {
      console.log('handleGoodsPrice--customerData==', this.customerData);
      if (!this.customerData || !this.customerData.id) return '';
      const skuOrder = this.customerData?.skuOrder || [];
      console.log('handleGoodsPrice--skuOrder==', skuOrder);
      console.log('handleGoodsPrice--!goods_id && !sku_id==', goods_id, sku_id);

      if (!goods_id && !sku_id) return '';
      const goodsSku = skuOrder.find(d => d.sku_id === sku_id);
      console.log('handleGoodsPrice--goodsSku==', sku_id, goodsSku);
      return goodsSku || {};
    },
    // 客户商品记录
    getCustomerRecord() {
      // if (!this.formData.customer_id) {
      //   return '';
      // }
      // const customerData = this.customerList.find(d => d.id === this.formData.customer_id);
      console.log('getCustomerRecord--customerData==', this.customerData);

      const skuOrder = this.customerData?.skuOrder || [];
      if (skuOrder.length) {
        const goods_record_str = skuOrder.map(d => {
          if (!d.sku_id) return '';
          const goodsItemStr = `${d.goods_name} ${d.sku} ${d.goods_price}元 ${this.$moment(d.create_time).format('YYYY-MM-DD')}`
          return goodsItemStr;
        })
        this.showCustomerRecord = false;
        return goods_record_str.join(', \n');
      }
      else {
        this.showCustomerRecord = true;
        return '';
      }
    },
    getCustomerRecord2() {
      console.log('getCustomerRecord--this.formData.customer_id==', this.formData);
      if (!this.formData.customer_id) {
        return '';
      }
      const row = this.customerList.find(d => d.id === this.formData.customer_id);
      if (row && row?.config) {
        // const config = JSON.parse(row.config);
        // const goods_record = config?.goods_record;
        const goods_record = this.goods_record || {}
        if (goods_record && Object.keys(goods_record).length) {
          console.log('getCustomerRecord--goods_record==', goods_record);
          const goods_record_str = Object.keys(goods_record).map(d => {
            console.log('d==', d);
            if (goods_record[d].length) {
              const goodsItem = goods_record[d].map(g => {
                const goodsItemStr = `${g.goods_name} ${g.goods_sku} ${g.goods_price}元 ${this.$moment(g.update_time).format('YYYY-MM-DD')}`
                return goodsItemStr;
              })
              return goodsItem.join(', \n')
            }
            else {
              return '';
            }
          })
          return goods_record_str.join(', \n');
        }
        else {
          return '';
        }
      }
      else {
        return '';
      }
    },
    updataComplete(prop, value) {
      if (prop === 'storeHouseList') {
        if (value.length === 1) {
          this.formData.store_house_id = value[0].id;
        }
      }
    },
    // 初始化数据
    async initFun() {
      if (this.customerList.length === 0) {
        this.$store.dispatch('customer/getCustomerList');
      }
    },
    // 获取订单详情；
    async getOrderDetails() {
      const { data } = await orderDetail({ id: this.pageParams.id });
      console.log('getOrderDetails==', data)
      let list = data?.goods_list || [];
      let goods_list = [];
      if (list.length) {
        goods_list = list.map(d => {
          const { total_price, discount_total_price } = this.handleGoodsItemPrice(d);
          d.total_price = total_price;
          d.discount_total_price = discount_total_price;
          if (d.config) {
            d.config = JSON.parse(d.config);
            d = { ...d.config, ...d };
          }
          return d;
        })
      }
      this.formData = { ...data, goods_list };
    },
    handleGoodsItemPrice(item) {
      if (!item) return;
      // 一个商品小计金额
      let total_price = parseFloat(item?.goods_price) * item?.goods_num;
      // 折后金额
      let discount_total_price = total_price * item?.discount;
      return { total_price, discount_total_price };
    },
    // 获取商品数据；
    async getGoods() {
      const { data } = await goodsIndex();
      this.goodsList = data?.list || [];
    },
    // 输入框值改变
    changeInput(value, index, prop) {
      console.log('changeInput==', value, index, prop);
      
      if (index < 0 || !prop) return;
      const goodsItem = this.formData.goods_list[index];
      // 折扣；
      switch (prop) {
        case 'goods_num': // 数量
          if (!value || value < 1) {
            this.$nextTick(() => {
              goodsItem.goods_num = 1;
            })
          }
          console.log('changeInput--goodsItem==', goodsItem)
          if (goodsItem.goods_num && goodsItem.goods_price) {
            goodsItem.total_price = goodsItem.goods_num * goodsItem.goods_price;
            goodsItem.goods_num2 = Math.floor(goodsItem.goods_num / goodsItem.unit_convert2);
            if (goodsItem.discount) {
              goodsItem.discount_price = goodsItem.goods_price * goodsItem.discount;
              goodsItem.discount_total_price = goodsItem.total_price * goodsItem.discount;
            }
          }
          // goodsItem.total_price = goodsItem.goods_num * goodsItem.goods_price;
          // goodsItem.goods_num2 = Math.floor(goodsItem.goods_num / goodsItem.unit_convert2);

          // goodsItem.discount_price = goodsItem.goods_price * goodsItem.discount;
          // goodsItem.discount_total_price = goodsItem.total_price * goodsItem.discount;
          break;
        case 'goods_num2':  // 数量2
          goodsItem.goods_num = goodsItem.goods_num2 * goodsItem.unit_convert2;

          goodsItem.total_price = goodsItem.goods_num * goodsItem.goods_price;
          goodsItem.discount_total_price = goodsItem.total_price * goodsItem.discount;
          break;
        case 'goods_price': // 单价
          if (!value || value <= 0) {
            this.$nextTick(() => {
              goodsItem.goods_price = 0.01;
              this.$message.warning(`温馨提示，第${index+1}个商品优惠力度爆表，请确认！`);
            })
          }
          goodsItem.goods_price = Number(Number(goodsItem.goods_price).toFixed(2));
          goodsItem.total_price = goodsItem.goods_num * goodsItem.goods_price;

          goodsItem.discount_price = goodsItem.goods_price * goodsItem.discount;
          goodsItem.discount_total_price = goodsItem.total_price * goodsItem.discount;
          break;
        case 'total_price': // 金额
          if (!value || value <= 0) {
            this.$nextTick(() => {
              goodsItem.goods_price = 0.01;
              this.$message.warning(`温馨提示，第${index+1}个商品优惠力度爆表，请确认！`);
            })
          }
          goodsItem.goods_price = parseFloat(parseFloat(goodsItem.total_price / goodsItem.goods_num).toFixed(2));

          goodsItem.discount_price = goodsItem.goods_price * goodsItem.discount;
          goodsItem.discount_total_price = goodsItem.total_price * goodsItem.discount;
          break;
        case 'discount':  // 折扣
          if (!value || value <= 0) {
            this.$nextTick(() => {
              goodsItem.discount = 0.01;
              this.$message.warning(`温馨提示，第${index+1}个商品优惠力度爆表，请确认！`);
            })
          }
          if (goodsItem.goods_price && value) {
            goodsItem.discount_price = goodsItem.goods_price * goodsItem.discount;
            goodsItem.discount_total_price = goodsItem.total_price * goodsItem.discount;
          }
          break;
        default:
          break;
      }
      this.$set(this.formData.goods_list, index, goodsItem)
    },
    // 新增组件返回；
    handleAddComCb(type, result) {
      console.log('handleAddComCb--', type, result);
      if (type === 'rowDblclick') {
        const goods_list = this.formData.goods_list || [];
        const goodsItem = this.goodsItem(result);
        console.log('handleAddComCb--goodsItem==', goodsItem);
        // 判断是否有多个仓库。如果只有一个则自动选择
        if (this.storeHouseList.length === 1) {
          goodsItem.store_house_id = this.storeHouseList[0].id;
        }
        // 获取用户历史购买价格
        const { goods_price, discount } = this.handleGoodsPrice(goodsItem.goods_id, goodsItem.sku_id);
        console.log('handleAddComCb===2==', goods_price, discount);
        if (goods_price && discount > 0.1) {
          goodsItem.goods_price = goods_price;
          goodsItem.total_price = goods_price * goodsItem.goods_num;
          goodsItem.discount = discount;
          goodsItem.discount_price = goods_price * discount;
        }
        if (this.goodsIndex < 0) {
          goods_list.push(goodsItem);
        }
        else {
          goods_list[this.goodsIndex] = goodsItem;
          // this.$set(this.formData.goods_list, this.goodsIndex, goodsItem)
          // this.$set(this.formData, 'goods_list', goods_list);
        }
        
        this.formData.goods_list = goods_list;
        this.$set(this.formData, 'goods_list', goods_list);
        const _this = this;
        this.$nextTick(() => {
          _this.$refs.tableRef.doLayout();
        })

        this.$refs.goodsDialofRef.closeDialog();
        console.log('handleAddComCb--this.formData==', this.formData);
      }
    },
    // table 操作按钮
    async handleTableOp(type) {
      if (type === 'orderDetail') { // 刷新 获取订单详情
        this.getOrderDetails();
      }
      else if (type === 'addGoods') { // 添加商品
        this.goodsIndex = -1;
        this.$refs.goodsDialofRef.showDialog('fetch');
      }
      else if (type === 'addOrder') { // 提交订单
        let isValid = false;
        this.$refs.orderForm.validate((valid) => {
          isValid = valid;
        });
        if (!isValid || this.saving) {
          console.log('addOrder--isValid, saving', isValid, this.saving);
          return
        }
        const goods_list = this.formData.goods_list || [];
        if (goods_list.length === 0) {
          this.$message.error('请选择商品');
          return;
        }
        goods_list.forEach(d => {
          d.config = JSON.stringify(d.config);
        })
        this.saving = true;
        try {
          const payload = {
            ...this.formData,
            goods_list,
          }
          console.log('addOrder--payload==', this.formData, payload);
          const res = await orderAdd(this.formData);
          if (res.code === 200) {
            this.$message.success('操作成功');
            // setTimeout(() => {
            //   this.$router.back();
            // }, 1000)
          }
          this.saving = false;
        } catch (e) {
          console.log('orderAdd--e==', e);
          this.saving = false;
        }
      }
    },
    // 处理table 单元格显示；
    handleRowResult(prop, row) {
      console.log('row==', row);
      if (prop === 'goods_name') {
        return `${row?.goods_name} ${row.sku}`
        // return `${row?.full_goods_name ? row?.full_goods_name : row?.goods_name} ${row.goods_sku}`
      }
      if (prop === 'goods_num2') {
        if (row.goods_num && row.unit_name2 && row.unit_convert !== row.unit_convert2 && row.unit_convert2) {
          const unitNum = row.goods_num % row.unit_convert2;
          const unitNum2 = Math.floor(row.goods_num / row.unit_convert2);
          return `${unitNum2}${row.unit_name2}${unitNum}${row.unit_name}`
        }
        return `${row.goods_num}${row.unait_name}`
      }
      if (prop === 'unit_convert2') {
        if (row.unit_convert && row.unit_convert2) {
          return `${row.unit_convert} * ${row.unit_convert2} ${row.unit_name}`
        }
        return '';
      }
      return row[prop] || '';
    },
    // table 合计；
    getSummaries(params) {
      const { columns, data } = params;
      console.log('getSummaries==', columns, data);

      const sums = [];
      if (data.length === 0) {
        return [];
      }
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        if (['goods_num', 'goods_num2', 'total_price', 'discount_total_price'].includes(column.property)) {
          let prop = column.property;
          if (prop === 'goods_num2') {
            prop = 'goods_num'
          }
          const values = data.map(item => Number(item[prop]));
          // if (!values.every(value => isNaN(value))) {
          let unitName = '';
          sums[index] = values.reduce((prev, curr, cIndex) => {
            if (column.property === 'goods_num') {
              unitName = data[cIndex].unit_name;
            }
            else if (column.property === 'goods_num2') {
              const unitNum = data[cIndex].goods_num % data[cIndex].unit_convert2;
              const unitNum2 = Math.floor(data[cIndex].goods_num / data[cIndex].unit_convert2);
              unitName = data[cIndex].unit_name2;
              if (prev && prev.length) {
                return [unitNum + prev[0], unitNum2 + prev[1]]
              }
              return [unitNum, unitNum2]
            }
            else if (column.property === 'total_price') {
              unitName = '元'
            }
            const value = Number(curr);

            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          if (column.property === 'goods_num') {
            console.log('goods_num--22sums==', sums, data[0])
            this.formData.total_num = sums[index];
            // sums[index] = sums[index] + data[0].unit_name;
            // console.log('goods_num--333==', sums)
          }
          if (column.property === 'goods_num2' && typeof (sums[index]) === 'object') {
            console.log('sums==', sums)
            let goods_num2 = 0;
            if (sums[index][1]) {
              goods_num2 = sums[index][1] + data[0].unit_name2
            }

            // if (sums[index][0]) {
            //   goods_num2 = goods_num2 + sums[index][0] + data[0].unit_name
            // }
            sums[index] = goods_num2;
          }
          if (column.property === 'total_price') {
            this.formData.total_price = Number(Number(sums[index]).toFixed(2));
            sums[index] = Number(sums[index]).toFixed(2);
            console.log('total_price--this.formData==', this.formData)
          }
          if (column.property === 'discount_total_price') {
            this.formData.discount_total_price = Number(Number(sums[index]).toFixed(2));
            sums[index] = Number(sums[index]).toFixed(2);
            console.log('total_price--this.formData==', this.formData)
          }
          // sums[index] += unitName;
          // } else {
          //   sums[index] = 'N/A';
          // }
        }
        else {
          sums[index] = '-';
        }
      });
      console.log('sums==', sums);
      return sums
    },
    // cellClick(row, column, cell, event) {
    //   console.log('cellClick--', row, column, cell, event);
    //   console.log('cellClick--2--', row.index, column.index);
    // },
    // 双击商品名称；
    handleDblclick(index, prop) {
      if (prop === 'goods_name') {
        this.goodsIndex = index;
        this.$refs.goodsDialofRef.showDialog('fetch');
      }
    },
    // 删除一行；
    handleDelRow(index) {
      this.formData.goods_list.splice(index, 1);
      this.$set(this.formData, 'goods_list', this.formData.goods_list)
    }
  }
}

</script>
<style lang="scss" scoped>
.print-mould-box {
  position: relative;
  &:before {
    content: "";
    position: absolute;
    width: 240mm;
    height: 140mm;
    border: 1px solid red;
    top: 30px;
    left: 50%;
    transform: translate(-50%, 0);
  }
}
.container-box {
  padding: 20px;
}

.table-box {
  // padding: 20px;
  margin-top: 10px;
  ::v-deep .el-form-item {
    margin-bottom: 0 !important;
    div,
    input {
      width: 100%;
    }
    .el-input-group__append {
      width: 40px;
      padding: 0;
    }
  }
  ::v-deep .el-table__footer {
    font-weight: bold;
    font-size: 16px;
  }
  .close_goods_row {
    color: #999;
    cursor: pointer;
  }
}
.form-table.el-table {
  ::v-deep .el-table__body {
    .el-table__cell {
      padding: 0;
      .cell {
        padding: 0;
        div {
          margin: 0;
          height: 40px;
          line-height: 40px;
        }
        input {
          height: 40px;
          line-height: 40px;
          border-width: 0px;
          text-align: center;
        }
        .el-form-item.is-error .el-input__inner {
          border-width: 1px;
        }
        .el-input-group__append {
          border: 0;
        }
      }
    }
  }
}

#print_demo {
  .header_box {
    text-align: center;
    font-size: 24px;
    font-weight: 800;
    .flex_row {
      display: flex;
      justify-content: space-between;
      font-size: 14px;
      font-weight: normal;
    }
  }
  .content_box {
  }
  .footer_box {
    color: #666;
  }
}
</style>
